package com.yaDuo.common.ui;

import android.app.Service;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.yaDuo.common.util.LogUtil;

import java.lang.reflect.Field;
import java.util.Locale;

/**
 * @author xiaolin
 * time 2021-05-04 02:55
 */
public class DpiUtils {

    private static final String TAG = "DpiUtils";

    /**
     * 填写设计图中屏幕的宽度（px），调用{@link #setCustomDensityByWidth)}会自动将当前屏幕的宽度设置为这么多dp，达到自动适配的目的
     * <b>注意：必须是float</b>
     */
    private static final float DESIGNED_SCREEN_WIDTH_DP = 768;

    /**
     * 填写设计图中屏幕的高度（px），调用{@link #setCustomDensityByHeight}会自动将当前屏幕的高度设置为这么多dp，达到自动适配的目的
     * <b>注意：必须是float</b>
     */
    private static final float DESIGNED_SCREEN_HEIGHT_DP = 600;

    /**
     * 修改DPI
     *
     * @param orgContext    用来获取显示区域大小，在平板设备上，显示区域会变化
     * @param targetContext 要修改的Context
     */
    public static void applyDpi(Context orgContext, Context targetContext) {
        int screenWidth = orgContext.getResources().getDisplayMetrics().widthPixels;
        int screenHeight = orgContext.getResources().getDisplayMetrics().heightPixels;
        LogUtil.d(TAG, String.format(Locale.getDefault(), "screenWidth=%d, screenHeight=%d", screenWidth, screenHeight));
        boolean isHor = screenHeight < screenWidth;// 横屏判断
        Log.d(TAG, "isHor:" + isHor);
        // 横屏
        if (isHor) {
            setCustomDensityByHeight(targetContext, screenHeight);
        }
        // 竖屏
        else {
            setCustomDensityByWidth(targetContext, screenWidth);
        }
    }

    /**
     * 除去状态栏的高度
     *
     * @return
     */
    public static int getScreenHeightNotStatusBar(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Service.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point outSize = new Point();
        if (display != null) {
            display.getSize(outSize);
        }

        int screenHeight = outSize.y;

        int statusBarHeight = 0;
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return screenHeight - statusBarHeight;
    }

    private static void setDensity(Context context, DisplayMetrics appDisplayMetrics, float targetDensity) {
        final int targetDensityDpi = (int) (160 * targetDensity);
        Log.d(TAG, "Target Density:" + targetDensity);
        Log.d(TAG, "Target Density:" + targetDensityDpi + "dpi");

        appDisplayMetrics.density = appDisplayMetrics.scaledDensity = targetDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;

        final DisplayMetrics activityDisplayMetrics = context.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = activityDisplayMetrics.scaledDensity = targetDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;

        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.densityDpi = targetDensityDpi;
        }
        resources.updateConfiguration(configuration, appDisplayMetrics);
    }

    /**
     * 根据宽度自适应布局
     *
     * @param context
     * @param width
     */
    public static void setCustomDensityByWidth(Context context, int width) {
        final DisplayMetrics appDisplayMetrics = context.getResources().getDisplayMetrics();
        final float targetDensity = width / DESIGNED_SCREEN_WIDTH_DP;
        setDensity(context, appDisplayMetrics, targetDensity);
    }

    /**
     * 根据高度自适应布局
     *
     * @param context
     * @param height
     */
    public static void setCustomDensityByHeight(Context context, int height) {
        final DisplayMetrics appDisplayMetrics = context.getResources().getDisplayMetrics();
        final float targetDensity = height / DESIGNED_SCREEN_HEIGHT_DP;
        setDensity(context, appDisplayMetrics, targetDensity);
    }
}
